package com.linkhouse.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.linkhouse.common.domain.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("file")
@Api("文件上传")
public class FileController {

    @PostMapping("upLoadFile")
    @ApiOperation("二手房源图片")
    @ApiImplicitParam(name = "myFile",value = "要上传的图片",required = true,paramType = "query")
    public Result upLoadFile(@RequestParam("myFile")MultipartFile myFile){
        String https = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tADY4ctcmGW793MuUqa";
        String accessKeySecret = "WQqjykVuHmcwPYKCa9EmfUFg2p5vYT";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dongdongshop2109";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/"+ myFile.getOriginalFilename();//.getOriginalFilename():获取图片自己的名字

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(https+endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        StringBuffer buffer = new StringBuffer();
        buffer.append(https).append(bucketName).append(".").append(endpoint).append("/").append(objectName);
                //https://dongdongshop2109.oss-cn-beijing.aliyuncs.com/image/7.jpg
        return Result.ok().setData(buffer.toString());
    }
}
